package com.daolion.utils.log;

import android.content.Context;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


public class LoggerUtils {
    public static BufferedWriter out;

    public static void log(Context context, String message){
        try {
            File logFile = getToadyLogFile(context);
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
            if (logFile.canWrite()) {
                FileWriter LogWriter = new FileWriter(logFile, true);
                out = new BufferedWriter(LogWriter);
                out.write(DateFormatterUtils.getLogContentDateFormat() + "   ");
            }
            out.write(message + "\n");
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public static File[] getAllLogFiles(Context context){
        File logDir = FileUtils.getLogDataDir(context);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        return logDir.listFiles(file -> {
            boolean isTxtFile = file.getName().endsWith(".txt");
            if (isTxtFile) {
                return true;
            }else {
                return false;
            }
        });
    }
    
    
    public static File getToadyLogFile(Context context){
        File logDir = FileUtils.getLogDataDir(context);
        if (!logDir.exists()) {
            logDir.mkdirs();
        }
        return new File(logDir, getTodayLogFileName());
    }
    
    /**
     * 返回昨天的 文件名
     *
     * @return * sample return is : d1_2018-08-12_ddddddddd.txt
     */
    public static String getBeforeDayLogFileName(){
        //获取前一天
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date time = cal.getTime();
        final String beforeDay = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(time);
        return beforeDay + ".txt";
    }
    
    
    /**
     * 返回今天的 文件名（不加.txt);
     *
     * @return * sample return is : d1_2018-08-12_ddddddddd.txt
     */
    public static String getTodayLogFileName(){
        //获取前一天
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 0);
        Date time = cal.getTime();
        final String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(time);
        return  today + ".txt";
    }
    
}
